import sys
import tkinter as tk
from tkinter import messagebox
from tkcalendar import DateEntry
from datetime import datetime
import requests
import json

# 定义计算校验和的函数
def calculate_checksum(data):
    combined_str = ""
    # 遍历数据字典，将键值对组合成字符串
    for key, value in data.items():
        if isinstance(value, dict):
            # 如果值是字典，递归调用计算校验和的函数
            combined_str += calculate_checksum(value)
        else:
            combined_str += str(value)
    # 计算 ASCII 码总和
    ascii_sum = sum(ord(c) for c in combined_str)
    # 对 100 取模
    return str(ascii_sum % 100)

def query_data():
    # 获取用户选择的值
    start_date = date_start.get()
    start_hour = spin_start_hour.get()
    start_minute = spin_start_minute.get()
    start_second = "00"  # 假设秒为00，也可以添加Spinbox让用户选择
    end_date = date_end.get()
    end_hour = spin_end_hour.get()
    end_minute = spin_end_minute.get()
    end_second = "00"

    # 简单验证
    if not start_date or not end_date:
        messagebox.showerror("输入错误", "请选择开始和结束日期")
        return

    try:
        # 构造完整的开始时间和结束时间字符串
        start_datetime_str = f"{start_date} {start_hour}:{start_minute}:{start_second}"
        end_datetime_str = f"{end_date} {end_hour}:{end_minute}:{end_second}"

        # 尝试转换日期时间字符串为datetime对象以确保格式正确
        start_datetime = datetime.strptime(start_datetime_str, '%Y/%m/%d %H:%M:%S')
        end_datetime = datetime.strptime(end_datetime_str, '%Y/%m/%d %H:%M:%S')
    except ValueError:
        messagebox.showerror("输入错误", "日期或时间格式不正确")
        return

    # 构造要发送的JSON数据
    data = {
        "data": {
            "query_time_start": start_datetime.strftime('%Y%m%d%H%M%S'),
            "query_time_end": end_datetime.strftime('%Y%m%d%H%M%S'),
            "time": datetime.now().strftime('%Y%m%d%H%M%S'),
        },
        "machine_id": machine_id
    }

    # 计算校验和
    check_sum = calculate_checksum(data)
    data["data"]["check_sum"] = check_sum

    # 将数据转换为字符串格式
    data_str = json.dumps(data)
    print(data_str)

    # 发送POST请求
    try:
        response = requests.post('http://47.108.221.119:5000/query', json=data)
        if response.status_code == 200:
            messagebox.showinfo("成功", f"数据上传成功: {response.text}")
            # 清空显示框
            result_text.delete(1.0, tk.END)
            # 显示从服务器传来的数据
            result_text.insert(tk.END, json.dumps(response.json(), indent=4))
        else:
            messagebox.showerror("错误", f"数据上传失败: {response.status_code} - {response.text}")
    except requests.RequestException as e:
        messagebox.showerror("网络错误", f"请求过程中出现网络错误: {e}")


# 获取传递的机器码，如果未提供则设置默认值
machine_id = sys.argv[1] if len(sys.argv) > 1 else "未提供机器码"

root = tk.Tk()
root.title("数据查询")

# 标题标签
label_title = tk.Label(root, text="请填写查询条件", font=("Arial", 14))
label_title.pack(pady=10)

# 显示机器码
frame_machine_id_display = tk.Frame(root)
frame_machine_id_display.pack(pady=5)
label_machine_id_display = tk.Label(frame_machine_id_display, text=f"当前查询的机器码: {machine_id}")
label_machine_id_display.pack(side=tk.LEFT, padx=10)

# 开始日期选择器
frame_start_date = tk.Frame(root)
frame_start_date.pack(pady=5)
label_start_date = tk.Label(frame_start_date, text="开始日期:")
label_start_date.pack(side=tk.LEFT, padx=10)
date_start = DateEntry(frame_start_date, width=12, background='darkblue', foreground='white', borderwidth=2)
date_start.pack(side=tk.LEFT)

# 开始时间选择器
frame_start_time = tk.Frame(root)
frame_start_time.pack(pady=5)
label_start_time = tk.Label(frame_start_time, text="开始时间(HH:MM):")
label_start_time.pack(side=tk.LEFT, padx=10)
spin_start_hour = tk.Spinbox(frame_start_time, from_=0, to=23, format="%02.0f", width=4)
spin_start_hour.pack(side=tk.LEFT)
spin_start_minute = tk.Spinbox(frame_start_time, from_=0, to=59, format="%02.0f", width=4)
spin_start_minute.pack(side=tk.LEFT)

# 结束日期选择器
frame_end_date = tk.Frame(root)
frame_end_date.pack(pady=5)
label_end_date = tk.Label(frame_end_date, text="结束日期:")
label_end_date.pack(side=tk.LEFT, padx=10)
date_end = DateEntry(frame_end_date, width=12, background='darkblue', foreground='white', borderwidth=2)
date_end.pack(side=tk.LEFT)

# 结束时间选择器
frame_end_time = tk.Frame(root)
frame_end_time.pack(pady=5)
label_end_time = tk.Label(frame_end_time, text="结束时间(HH:MM):")
label_end_time.pack(side=tk.LEFT, padx=10)
spin_end_hour = tk.Spinbox(frame_end_time, from_=0, to=23, format="%02.0f", width=4)
spin_end_hour.pack(side=tk.LEFT)
spin_end_minute = tk.Spinbox(frame_end_time, from_=0, to=59, format="%02.0f", width=4)
spin_end_minute.pack(side=tk.LEFT)

# 查询按钮
button_query = tk.Button(root, text="查询", command=query_data)
button_query.pack(pady=10)

# 创建一个框架来放置文本框和滚动条
text_frame = tk.Frame(root)
text_frame.pack(pady=10)

# 添加显示框
result_text = tk.Text(text_frame, height=10, width=50)
result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# 添加垂直滚动条
scrollbar = tk.Scrollbar(text_frame, command=result_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 将滚动条与文本框关联
result_text.config(yscrollcommand=scrollbar.set)

root.mainloop()